<template>
  <div class="star-message">
    <!-- 星空背景 -->
    <canvas id="bgCanvas"></canvas>

    <!-- 弹幕留言层 -->
    <div class="barrage-container">
      <div
        v-for="msg in activeMessages"
        :key="msg.id"
        class="barrage"
        :style="{
          top: msg.top + 'px',
          animationDuration: msg.duration + 's'
        }"
      >
        {{ msg.content }}
      </div>
    </div>

    <!-- 输入留言 -->
    <div class="input-area">
      <a-input
        v-model:value="newMsg"
        :placeholder="isMobile ? '说点什么...' : '说点什么吧...'"
        style="width: 60%; margin-right: 10px;"
        @keyup.enter="sendMessage"
        class="message-input"
        :maxlength="200"
      />
      <a-button type="primary" @click="sendMessage" class="send-button">发送</a-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from "vue";
import { message } from "ant-design-vue";

// 移动端检测
const isMobile = ref(false);
const checkIsMobile = () => {
  return window.innerWidth <= 768;
};
// 星空背景数据
let starCanvas, bgCtx, animationId;
let shootingStars = [];
let twinkleStars = [];
import request from "../../api/server";
// 弹幕相关数据
const messages = ref([]);
const activeMessages = ref([]);
const newMsg = ref("");
let batchIndex = 0;
let loopTimer = null;

// 模拟弹幕数据
const mockData = ref([
  "夜空真美！",
  "你好呀，博主！",
  "Vue3真强大！",
  "TypeScript真香！",
  "写代码的夜晚最安静。",
  "一起加油！",
  "全栈梦想中🔥",
  "BUG退散！",
  "学习使人快乐！",
  "今天的星空格外明亮~",
]);
const getMockData = async () => {
  try {
    const res = await request.get("/api/getContact")
    
    if (res.status === 200 && res.data.content) {
      // 将新数据添加到数组末尾，而不是替换
      const newContents = res.data.content.map(item => item.content)
      
      mockData.value.push(...newContents)
      
      // 数据加载完成后，重新初始化弹幕池
      initBarrage()
      message.success(`成功加载 ${newContents.length} 条新弹幕！`)
    } else {
    }
  } catch (error) {
    message.error('获取弹幕数据失败，请检查网络连接')
  }
}

// 初始化所有弹幕池（分批循环播放）
const initBarrage = () => {
  // 如果已经有定时器，先清除避免重复
  if (loopTimer) {
    clearInterval(loopTimer)
  }
  
  messages.value = mockData.value.map((text, i) => ({
    id: i + "_" + Date.now(),
    content: text,
    top: Math.random() * window.innerHeight * 0.7 + 50,
    duration: 12 + Math.random() * 5
  }));

  // 首批立即展示
  playBatch();

  // 定时循环播放
  loopTimer = setInterval(() => {
    playBatch();
  }, 1000 * 16); // 每批弹幕大约持续 16 秒
};

// 每次播放一批弹幕
const playBatch = () => {
  const batchSize = isMobile.value ? 5 : 10; // 移动端减少弹幕数量
  const start = (batchIndex * batchSize) % messages.value.length;
  const end = start + batchSize;

  // 当前批次
  const batch = messages.value.slice(start, end);

  // 延迟0.5秒清理旧弹幕 → 再添加新弹幕
  setTimeout(() => {
    activeMessages.value = [];
    setTimeout(() => {
      activeMessages.value = batch.map((msg) => ({
        ...msg,
        top: Math.random() * window.innerHeight * (isMobile.value ? 0.6 : 0.7) + (isMobile.value ? 60 : 40),
        duration: (isMobile.value ? 8 : 12) + Math.random() * (isMobile.value ? 3 : 4)
      }));
    }, 500);
  }, 0);

  batchIndex++;
};

// 发送新留言
const sendMessage = () => {
  const content = newMsg.value.trim();
  if (!content) {
    message.warning("请输入内容！");
    return;
  }
  
  mockData.value.push(content)

  const msg = {
    id: Date.now() + "_" + Math.random(),
    content: content,
    top: Math.random() * window.innerHeight * 0.7 + 50,
    duration: 12 + Math.random() * 3
  };

  // 新留言立即加入并飞入屏幕
  activeMessages.value.push(msg);
  messages.value.push(msg);
  newMsg.value = "";
  message.success("留言发送成功！");

  // 发留言时加一个流星特效
  shootingStars.push({
    x: Math.random() * starCanvas.width,
    y: 0,
    length: Math.random() * 100 + 50,
    speed: Math.random() * 3 + 2,
    opacity: 1
  });
  
  // 移动端优化：收起键盘
  if (window.innerWidth <= 768) {
    document.activeElement.blur();
  }
};

// ---------------- 星空背景 ----------------
const initStarBackground = () => {
  starCanvas = document.getElementById("bgCanvas");
  if (!starCanvas) return;

  bgCtx = starCanvas.getContext("2d");
  starCanvas.width = window.innerWidth;
  starCanvas.height = window.innerHeight;

  createTwinkleStars();
  animateStars();
};

const createTwinkleStars = () => {
  for (let i = 0; i < 200; i++) {
    twinkleStars.push({
      x: Math.random() * starCanvas.width,
      y: Math.random() * starCanvas.height,
      size: Math.random() * 2 + 0.5,
      brightness: Math.random(),
      twinkleSpeed: Math.random() * 0.02 + 0.01
    });
  }
};

const animateStars = () => {
  bgCtx.fillStyle = "#000011";
  bgCtx.fillRect(0, 0, starCanvas.width, starCanvas.height);

  twinkleStars.forEach((star) => {
    star.brightness += star.twinkleSpeed;
    if (star.brightness > 1 || star.brightness < 0) {
      star.twinkleSpeed = -star.twinkleSpeed;
    }

    bgCtx.fillStyle = `rgba(255, 255, 255, ${star.brightness})`;
    bgCtx.beginPath();
    bgCtx.arc(star.x, star.y, star.size, 0, Math.PI * 2);
    bgCtx.fill();
  });

  shootingStars = shootingStars.filter((star) => {
    star.x -= star.speed;
    star.y += star.speed;
    star.opacity -= 0.02;

    if (star.opacity > 0 && star.x > 0 && star.y < starCanvas.height) {
      bgCtx.strokeStyle = `rgba(255, 255, 255, ${star.opacity})`;
      bgCtx.lineWidth = 2;
      bgCtx.beginPath();
      bgCtx.moveTo(star.x, star.y);
      bgCtx.lineTo(star.x + star.length, star.y - star.length);
      bgCtx.stroke();
      return true;
    }
    return false;
  });

  if (Math.random() < 0.004) {
    shootingStars.push({
      x: Math.random() * starCanvas.width,
      y: 0,
      length: Math.random() * 100 + 50,
      speed: Math.random() * 3 + 2,
      opacity: 1
    });
  }

  animationId = requestAnimationFrame(animateStars);
};

onMounted(() => {
  // 检测是否为移动端
  isMobile.value = checkIsMobile();
  
  // 监听窗口大小变化
  const handleResize = () => {
    isMobile.value = checkIsMobile();
    // 重新设置画布大小
    if (starCanvas) {
      starCanvas.width = window.innerWidth;
      starCanvas.height = window.innerHeight;
    }
  };
  
  window.addEventListener('resize', handleResize);
  
  initStarBackground();
  // 先初始化本地弹幕，让用户立即看到内容
  initBarrage();
  // 然后异步加载更多弹幕数据
  getMockData()
  
  // 清理函数
  onUnmounted(() => {
    window.removeEventListener('resize', handleResize);
  });
});

onUnmounted(() => {
  if (animationId) cancelAnimationFrame(animationId);
  if (loopTimer) clearInterval(loopTimer);
  shootingStars = [];
  twinkleStars = [];
});
</script>

<style scoped>
.star-message {
  position: relative;
  width: 100%;
  height: 100vh;
  overflow: hidden;
  color: #fff;
  background-color: #000;
}

/* 星空画布 */
#bgCanvas {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 0;
  width: 100%;
  height: 100%;
}

/* 弹幕层 */
.barrage-container {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
  pointer-events: none;
  z-index: 2;
}

.barrage {
  position: absolute;
  white-space: nowrap;
  font-size: 18px;
  color: #fff;
  text-shadow: 0 0 6px #6df;
  animation: moveLeft linear forwards;
}

@keyframes moveLeft {
  from {
    transform: translateX(100vw);
    opacity: 0;
  }
  5% {
    opacity: 1;
  }
  95% {
    opacity: 1;
  }
  to {
    transform: translateX(-100%);
    opacity: 0;
  }
}

/* 输入框 */
.input-area {
  position: absolute;
  bottom: 30px;
  width: 100%;
  text-align: center;
  z-index: 3;
  padding: 0 20px;
  box-sizing: border-box;
}

/* 输入框和按钮样式 */
.message-input {
  height: 40px;
  font-size: 16px;
}

.send-button {
  height: 40px;
  font-size: 16px;
  padding: 0 20px;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .input-area {
    bottom: 20px;
    padding: 0 15px;
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 10px;
  }
  
  .message-input {
    width: 70% !important;
    height: 44px;
    font-size: 16px;
    margin-right: 0 !important;
  }
  
  .send-button {
    height: 44px;
    font-size: 16px;
    padding: 0 15px;
    min-width: 60px;
  }
  
  .barrage {
    font-size: 14px;
  }
}

@media (max-width: 480px) {
  .input-area {
    bottom: 10px;
    padding: 0 10px;
  }
  
  .message-input {
    width: 65% !important;
    height: 42px;
    font-size: 14px;
  }
  
  .send-button {
    height: 42px;
    font-size: 14px;
    padding: 0 12px;
    min-width: 50px;
  }
  
  .barrage {
    font-size: 12px;
  }
}

/* 横屏适配 */
@media (max-height: 500px) {
  .input-area {
    bottom: 5px;
    padding: 0 5px;
  }
  
  .message-input {
    width: 60% !important;
    height: 36px;
    font-size: 12px;
  }
  
  .send-button {
    height: 36px;
    font-size: 12px;
    padding: 0 10px;
    min-width: 45px;
  }
  
  .barrage {
    font-size: 10px;
  }
}
</style>
